/* File containing accessory functions common to all scripts */
/* v0.0.1 JUN-12-2020 */

set more off

/* PATHS */
do "code/config.do"

cap program drop _all

/* edit CSV files prepped by python code */

program define linkTransitStops
   python script "code/1a_linkTransitStops.py"
   
   frame create bus
   frame create mrt
   
   frame bus {
	   cap clear
	   import delimited "make_data/bus_stop_subzones.csv", colrange(2) case(upper)
	   drop BUS_STOP_CD BUS_STOP_NAM RD_NAM
	   gsort MRK_ID_NUM
	   ren MRK_ID_NUM JRNY_ORIG_ID_NUM /* rename variables */
	   gen int JRNY_DEST_ID_NUM = JRNY_ORIG_ID_NUM
	   save "make_data/bus_stop_subzones.dta", replace
	   }
   frame mrt {
	   cap clear
	   import delimited "make_data/mrt_station_subzones.csv", colrange(2) case(upper)
	   drop STATION ID
	   gsort STN_ID_NUM
	   ren STN_ID_NUM JRNY_ORIG_ID_NUM
	   gen int JRNY_DEST_ID_NUM = JRNY_ORIG_ID_NUM
	   save "make_data/mrt_station_subzones.dta", replace
	   }
   
   frame drop bus
   frame drop mrt	
end


/* merge with bus and mrt subzones. program to do this */
program define mergeSubzones
	local upper1 = upper("`1'")  /* generates uppercase name */
	merge m:m JRNY_`upper1'_ID_NUM ///
	  using "make_data/bus_stop_subzones.dta", generate(`1'_bus_merged) keep(1 3)
   ren SUBZONE `1'_bus_area
   ren PLANNING_AREA `1'_bus_pl
   
   merge m:m JRNY_`upper1'_ID_NUM ///
	  using "make_data/mrt_station_subzones.dta", generate(`1'_mrt_merged) keep(1 3)
   ren SUBZONE `1'_mrt_area
   ren PLANNING_AREA `1'_mrt_pl
   
   gen `1'_area = `1'_bus_area if `1'_bus_merged == 3
   replace `1'_area = `1'_mrt_area if `1'_mrt_merged == 3
   gen `1'_pl = `1'_bus_pl if `1'_bus_merged == 3
   replace `1'_pl = `1'_mrt_pl if `1'_mrt_merged == 3
   /* drop if `1'_area == ""  */
   drop `1'_bus_* `1'_mrt_*
	
	cap macro drop upper1 /* garbage cleaning */
end

/* accessory functions end here */
